﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using Portal.Web.Model;
using Portal.Web.Utility;
using Portal.Exam.Bussiness;
using Portal.Core;


namespace Portal.Exam.Render
{
    public class ExamTemplate
    {
        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut Draw(string SiteId)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {

                WebSessionUtility.CheckSessionTimeOut();
                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                string IconRoot = WebConfig.GetButtonIconRoot(OSiteParam);

                bool CheckAllowManage = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CheckPermission(SiteId, ExamPermission.StaticId, ExamPermission.funcExamTemplateManage, ExamPermission.StaticId, WebSessionUtility.GetCurrentLoginUser().UserId, false);

                StringBuilder RetHtml = new StringBuilder();
                RetHtml.Append(

                #region Javascript
"<script language=javascript> \r\n" +

                    "    function ClientLoadRecord(Id)\r\n" +
                   "    {\r\n" +
                   "        document.getElementById('txtSelectedUserType').value=Id;\r\n" +
                   "        ClientReading();\r\n" +
                   "    }\r\n" +

                    "    function ClientReading()\r\n" +
                   "    {\r\n" +
                   "        SiteId='" + SiteId + "';\r\n" +
                   "        UserType = document.getElementById('txtSelectedUserType').value;\r\n" +
                   "        Keyword = document.getElementById(\"txtKeyword\").value; \r\n" +
                   "        AjaxOut = Portal.Exam.Render.ExamTemplate.ServerSideReadingExamTemplate(SiteId,Keyword,UserType,0).value;\r\n" +
                   "        if(AjaxOut.Error)\r\n" +
                   "        {\r\n" +
                   "            alert(AjaxOut.InfoMessage);\r\n" +
                   "            return;\r\n" +
                   "        }\r\n" +
                   "        document.getElementById('divListItemContent').innerHTML = AjaxOut.HtmlContent;\r\n" +
                   "    }\r\n" +

                    "function ClientDeleteExamTemplate(ExamTemplateId) { \r\n" +
                    "    SiteId='" + SiteId + "';\r\n" +
                    "    Msg = Portal.Exam.Render.ExamTemplate.ServerSideCheckDeleteExamTemplate(SiteId).value; \r\n" +
                    "    if (Msg.indexOf(\"ERROR\") != -1) { \r\n" +
                    "        alert(Msg); \r\n" +
                    "        return; \r\n" +
                    "    } \r\n" +

                    "    Msg = 'Bạn đã chắc chắn xóa chưa?'; \r\n" +
                    "    if (confirm(Msg) == false) return; \r\n" +
                    "    RetValue = Portal.Exam.Render.ExamTemplate.ServerSideDeleteExamTemplate(SiteId, ExamTemplateId).value; \r\n" +
                    "    if (RetValue.indexOf(\"ERROR\") != -1) { \r\n" +
                    "        alert(RetValue); \r\n" +
                    "        return; \r\n" +
                    "    } \r\n" +
                    "    alert(RetValue); \r\n" +
                    "    RealJumpPageExamTemplate(); \r\n" +
                    "} \r\n" +


                    "function JumPageExamTemplate(PageIndex) { \r\n" +
                    "   document.getElementById('txtPageIndex').value=PageIndex;\r\n" +
                    "   document.getElementById(\"divProcessing\").innerHTML = 'Đang đọc dữ liệu từ máy chủ...'; \r\n" +
                    "   setTimeout(\"RealJumpPageExamTemplate()\", 10); \r\n" +
                    "} \r\n" +

                    "function RealJumpPageExamTemplate() { \r\n" +
                    "    SiteId='" + SiteId + "';\r\n" +
                    "    PageIndex = document.getElementById(\"txtPageIndex\").value; \r\n" +
                    "    Keyword = document.getElementById(\"txtKeyword\").value; \r\n" +
                    "    UserType = document.getElementById('txtSelectedUserType').value;\r\n" +
                    "    AjaxOut = Portal.Exam.Render.ExamTemplate.ServerSideReadingExamTemplate(SiteId, Keyword,UserType, PageIndex).value; \r\n" +
                    "        if(AjaxOut.Error)\r\n" +
                    "        {\r\n" +
                    "            alert(AjaxOut.InfoMessage);\r\n" +
                    "            return;\r\n" +
                    "        }\r\n" +
                    "    document.getElementById(\"divProcessing\").innerHTML = \"\"; \r\n" +
                    "        document.getElementById('divListItemContent').innerHTML = AjaxOut.HtmlContent;\r\n" +
                    "} \r\n" +


                   "    function ClientAddExamTemplate()\r\n" +
                   "    {\r\n" +
                   "         SelectedNode = $(\"#tree\").dynatree(\"getActiveNode\");\r\n" +
                   "         if(SelectedNode==null)\r\n" +
                   "         {\r\n" +
                   "            alert('Chưa xác định vào nhóm cần thêm!');\r\n" +
                   "            return;\r\n" +
                   "         }\r\n" +

                   "        AccountType = SelectedNode.data.href;\r\n" +
                   "        if(AccountType=='root')\r\n" +
                   "        {\r\n" +
                   "            alert('Chưa xác định vào nhóm cần thêm! Không thể thêm vào nhóm gốc!');\r\n" +
                   "            return;\r\n" +
                   "        }\r\n" +
                   "        window.open('AddExamTemplate.aspx?AccountType='+AccountType,'_self');\r\n" +
                   "    }\r\n" +


                    "function ClientViewExamTemplate(ExamTemplateId) { \r\n" +
                    "    SiteId='" + SiteId + "';\r\n" +
                    "    Url = Portal.Exam.Render.ExamTemplate.GetViewExamUrl(SiteId,ExamTemplateId).value; \r\n" +
                    "    if (Url.indexOf(\"ERROR\") != -1) { \r\n" +
                    "        alert(Url); \r\n" +
                    "        return; \r\n" +
                    "    } \r\n" +
                    "    window.open(Url, '_blank'); \r\n" +
                    "} \r\n" +

                    "function ClientUpdateExamTemplate(ExamTemplateId,UserType) { \r\n" +
                    "    SiteId='" + SiteId + "';\r\n" +
                    "    Url = Portal.Exam.Render.ExamTemplate.GetUpdateExamUrl(SiteId,ExamTemplateId,UserType).value; \r\n" +
                    "    if (Url.indexOf(\"ERROR\") != -1) { \r\n" +
                    "        alert(Url); \r\n" +
                    "        return; \r\n" +
                    "    } \r\n" +
                    "    window.open(Url, '_self'); \r\n" +
                    "} \r\n" +


                   "    function ClientAdd()\r\n" +
                   "    {\r\n" +
                   "         SelectedNode = $(\"#tree\").dynatree(\"getActiveNode\");\r\n" +
                   "         if(SelectedNode==null)\r\n" +
                   "         {\r\n" +
                   "            alert('Chưa xác định vào nhóm cần thêm!');\r\n" +
                   "            return;\r\n" +
                   "         }\r\n" +

                   "        AccountType = SelectedNode.data.href;\r\n" +
                   "        if(AccountType=='root')\r\n" +
                   "        {\r\n" +
                   "            alert('Chưa xác định vào nhóm cần thêm! Không thể thêm vào nhóm gốc!');\r\n" +
                   "            return;\r\n" +
                   "        }\r\n" +
                   "        window.open('AddGroupQuestion.aspx?AccountType='+AccountType,'_self');\r\n" +
                   "    }\r\n" +

                   "    function ClientUpdate(GroupQuestionId)\r\n" +
                   "    {\r\n" +
                   "        window.open('UpdateGroupQuestion.aspx?GroupQuestionId='+GroupQuestionId,'_self');\r\n" +
                   "    }\r\n" +

                   "    function ClientDelete(Id)\r\n" +
                   "    {\r\n" +
                   "        SiteId='" + SiteId + "';\r\n" +
                   "        if(confirm('Bạn đã chắc chắn xóa chưa?')==false)return;\r\n" +
                   "        UserType = document.getElementById('txtSelectedUserType').value;\r\n" +
                   "        AjaxOut = Portal.Exam.Render.GroupQuestionRenderBll.ServerSideDeleteGroupQuestion(SiteId,Id,UserType).value;\r\n" +
                   "        if(AjaxOut.Error)\r\n" +
                   "        {\r\n" +
                   "            alert(AjaxOut.InfoMessage);\r\n" +
                   "            return;\r\n" +
                   "        }\r\n" +
                   "        document.getElementById('divListItemContent').innerHTML=AjaxOut.HtmlContent;\r\n" +
                   "    }\r\n" +

                    "</script>\r\n" +

                #endregion

 " <input id=\"txtSelectedUserType\" type=\"hidden\">\r\n" +
                    "<input id=txtPageIndex type=hidden value=\"0\">\r\n" +

                    " <div class=FormFunction id=divListForm>\r\n" +
                    " <div class=DatabaseFunction>\r\n" +
                    "        <ul>\r\n");
                if (CheckAllowManage)
                {
                    RetHtml.Append(
                "            <li onclick=\"javascript:ClientAddExamTemplate();\"><img class=image src=\"" + IconRoot + "/Add.png\"><div>Thêm mới</div></li>\r\n");
                }
                RetHtml.Append(
                "            <li onclick=\"javascript:JumPageExamTemplate(0);\"><img class=image src=\"" + IconRoot + "/Refresh.png\"><div>Đọc lại</div></li>\r\n" +
                "            <li onclick=\"javascript:window.open('../../folder.aspx?folder=exam','_self');\"><img class=image src=\"" + IconRoot + "/back.png\"><div>Quay lại</div></li>\r\n" +
                "        </ul>\r\n" +
                "  </div>\r\n" +
                "    <div id=\"divListItems\">\r\n" +
               "        <table>\r\n" +
               "        <tr>\r\n" +
               "            <td class=col1>\r\n" +
               "                <div class=CssTreeView>\r\n" +
                                    ExamUltility.DrawTreeViewByAccountType(SiteId, WebSessionUtility.GetCurrentLoginUser().UserId).HtmlContent +
               "                </div>\r\n" +
               "            </td>\r\n" +
               "            <td class=col2>\r\n" +
               "                <div id=divListItemContent>\r\n" +
                                    ServerSideReadingExamTemplate(SiteId, "", "", 0).HtmlContent +
               "                </div>\r\n" +
               "            </td>\r\n" +
               "        </tr>\r\n" +
               "        </table>\r\n" +
               "    </div>\r\n" +
                "</div>\r\n");

                OAjaxOut.HtmlContent = RetHtml.ToString();
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.HtmlContent = ex.Message.ToString();
                OAjaxOut.InfoMessage = ex.Message.ToString();
            }
            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut ServerSideReadingExamTemplate(
            string SiteId,
            string Keyword,
            string UserType,
            int CurrentPageIndex)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                StringBuilder RetHtml = new StringBuilder();
                DataTable dtExamTemplate = new ExamTemplateBll().ReadingExamTemplateForAccountType(SiteId, Keyword, UserType);
                ReturnPaging OReturnPaging = WebPaging.GetPaging(dtExamTemplate.Rows.Count, CurrentPageIndex, 25, 10, "JumPageExamTemplate");
                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                string IconRoot = WebConfig.GetButtonIconRoot(OSiteParam);

                RetHtml.Append(
                    "   <h3>Danh sách các mẫu đề thi</h3>\r\n" +
                    "   <div id=divProcessing></div>" +
                    "   <div class=\"tabFunction\">Từ khóa: <input id=txtKeyword value=\"" + Keyword + "\"><input type=button class=button value=\"Lọc\" onclick=JumPageExamTemplate(0);></div>\r\n" +
                            OReturnPaging.PagingText +
                        "   <div class=\"tabcontent\">\r\n");
                if (dtExamTemplate.Rows.Count == 0)
                {
                    RetHtml.Append(
                        "<div class=CssNoData>Chưa có mẫu đề thi nào</div>\r\n");
                }
                else
                {
                    RetHtml.Append(

                        "   <table>" +
                        "       <tr>" +
                        "           <th>Stt</th>" +
                        "           <th>Mẫu đề thi</th>" +
                        "           <th></th>" +
                        "           <th></th>" +
                        "           <th></th>" +
                        "       </tr>");

                    for (int iIndex = OReturnPaging.StartIndex; iIndex < OReturnPaging.EndIndex; iIndex++)
                    {
                        string ExamTemplateId = (string)dtExamTemplate.Rows[iIndex]["ExamTemplateId"];

                        bool CheckfuncAccess = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CheckPermission(SiteId, ExamTemplatePermission.StaticId, ExamTemplatePermission.funcAccess, ExamTemplateId, WebSessionUtility.GetCurrentLoginUser().UserId, false);
                        if (!CheckfuncAccess) continue;

                        bool CheckfuncManage = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CheckPermission(SiteId, ExamTemplatePermission.StaticId, ExamTemplatePermission.funcManage, ExamTemplateId, WebSessionUtility.GetCurrentLoginUser().UserId, false);

                        string ExamTemplateName = (string)dtExamTemplate.Rows[iIndex]["ExamTemplateName"];
                        string ExamTemplateCat = string.Empty;
                        try
                        {
                            ExamTemplateCat = (string)dtExamTemplate.Rows[iIndex]["Category"];
                        }
                        catch
                        {
                            ExamTemplateCat = string.Empty;
                        }
                        string SubHtml = string.Empty;
                        if (!string.IsNullOrEmpty(ExamTemplateCat) && ExamTemplateCat.ToLower().Equals("freetext"))
                        {
                            SubHtml = "<td class=TdUpdateCol><input type=button class=button value=\"In\" onclick=\"javascript:ClientViewExamTemplate('" + ExamTemplateId + "');\"></td>";
                        }

                        RetHtml.Append(
                            "       <tr onMouseOver=\"this.className='highlight'\" onMouseOut=\"this.className='normal'\">" +
                            "           <td class=cssTdIndex>" + (iIndex + 1) + "</td>" +
                            "           <td>" + ExamTemplateName + "</td>");
                        if (CheckfuncManage)
                        {
                            RetHtml.Append(
                                "           <td class=TdUpdateCol><input type=button class=button value=\"Sửa\" onclick=\"javascript:ClientUpdateExamTemplate('" + ExamTemplateId + "','" + UserType + "');\"></td>" +
                                "           <td class=TdUpdateCol><input type=button class=button value=\"Xóa\" onclick=\"javascript:ClientDeleteExamTemplate('" + ExamTemplateId + "');\"></td>" +
                                "           <td class=TdUpdateCol><input type=button class=button value=\"Quản lý câu hỏi\" onclick=\"javascript:window.open('TemplateGroupQuestionTreeView.aspx?EId=" + ExamTemplateId + "&AccountType=" + UserType + "','_self');\" value=\"Quản lý\"></td>\r\n");
                        }
                        else
                        {
                            RetHtml.Append(
                                "   <td></td>\r\n" +
                                "   <td></td>\r\n" +
                                "           <td class=TdUpdateCol><input type=button class=button value=\"Quản lý câu hỏi\" onclick=\"javascript:window.open('TemplateGroupQuestionTreeView.aspx?EId=" + ExamTemplateId + "&AccountType=" + UserType + "','_self');\" value=\"Quản lý\"></td>\r\n");
                        }
                        RetHtml.Append(
                                SubHtml +
                        "       </tr>");
                    }
                    RetHtml.Append(
                        "   </table>\r\n" +
                        "</div>\r\n");
                }
                OAjaxOut.HtmlContent = RetHtml.ToString();
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
            }
            return OAjaxOut;
        }




        [AjaxPro.AjaxMethod]
        public string GetAddExamUrl(string SiteId)
        {
            try
            {
                WebSessionUtility.CheckSessionTimeOut();
                return "AddExamTemplate.aspx";
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }


        [AjaxPro.AjaxMethod]
        public string GetConfirmDeleteMsg(string SiteId)
        {
            return "Bạn đã chắc chắn xóa chưa?";
        }


        [AjaxPro.AjaxMethod]
        public string ServerSideCheckDeleteExamTemplate(string SiteId, string ExamTemplateId)
        {
            try
            {
                WebSessionUtility.CheckSessionTimeOut();
                return "";
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public string ServerSideDeleteExamTemplate(string SiteId, string ExamTemplateId)
        {
            try
            {
                WebSessionUtility.CheckSessionTimeOut();
                new ExamTemplateBll().DeleteExamTemplate(null, SiteId, ExamTemplateId);
                return "Xóa thành công";
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public string GetUpdateExamUrl(
            string SiteId, 
            string ExamTemplateId,
            string UserType)
        {
            try
            {
                WebSessionUtility.CheckSessionTimeOut();
                string UpdateUrl = "UpdateExamTemplate.aspx?ExamTemplateId=" + ExamTemplateId + "&AccountType=" + UserType;
                return UpdateUrl;
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public string GetViewExamUrl(
            string SiteId,
            string ExamTemplateId,
            string TotalExamTime)
        {
            try
            {
                WebSessionUtility.CheckSessionTimeOut();
                string UpdateUrl = "ViewExamTemplate.aspx?ExamTemplateId=" + ExamTemplateId;
                return UpdateUrl;
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }


        public static AjaxOut DrawForStudent(string SiteId, DataTable dtExamQuestion)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                string RetHtml =
                    " <div class=header>\r\n" +
                    "     <table>\r\n" +
                    "           <tr>\r\n" +
                    "               <td class=c1>\r\n" +
                    "                   <div>BỘ GIÁO DỤC VÀ ĐÀO TẠO</div>\r\n" +
                    "                   <div>Trường đại học Y Hải Phòng</div>\r\n" +
                    "               </td>\r\n" +
                    "               <td class=cmid>&nbsp;</td>\r\n" +
                    "               <td class=c2>\r\n" +
                    "                   <div>CỘNG HÒA XÃ HỘI CHỦ NGHĨA VIỆT NAM</div>\r\n" +
                    "                   <div>Độc lập - Tự do - Hạnh phúc</div>\r\n" +
                    "                   <div> -----------oOo------------</div>\r\n" +
                    "               </td>\r\n" +
                    "           </tr>\r\n" +
                    "     </table>\r\n" +
                    " </div>\r\n" +
                    " <div class=CssHeading>Đề thi cho thí sinh - ..................../......................................./ Số điểm: ...................</div>\r\n" +
                    " <div class=CssExamInfo>Môn thi: .........................</div>\r\n" +
                    " <div class=CssMarkInfo>\r\n" +
                    "       <table>\r\n" +
                    "           <tr>\r\n" +
                    "               <td class=c1>Điểm thi của bài thi</td>\r\n" +
                    "               <td class=c2>Họ tên và chữ ký</td>\r\n" +
                    "               <td class=c3>Số phách<div>(Do chủ tịch HD chấm ghi chú)</div></td>\r\n" +
                    "           </tr>\r\n" +
                    "           <tr>\r\n" +
                    "               <td class=c1><table class=tdInner><tr><td>Bằng số</td><td>Bằng chữ</td></tr></table></td>\r\n" +
                    "               <td class=c2><div class=CssAlignLeft>Giáo khảo 1</div><div class=CssAlignLeft>.........................................................................</div><div class=CssAlignLeft>Giáo khảo 2</div><div class=CssAlignLeft>.........................................................................</div></td>\r\n" +
                    "               <td class=c3></td>\r\n" +
                    "           </tr>\r\n" +
                    "       </table>\r\n" +
                    " </div>\r\n" +
                    " <div class=CssStartExam>Hoàn thành " + dtExamQuestion.Rows.Count.ToString("#,##") + " câu hỏi dưới đây</div>\r\n" +
                    " <div class=CssExamContent>\r\n" +
                    " <ul>\r\n";

                for (int iIndex = 0; iIndex < dtExamQuestion.Rows.Count; iIndex++)
                {
                    string ExamQuestionId = (string)dtExamQuestion.Rows[iIndex]["ExamQuestionId"];
                    RetHtml += "  <li>" + DrawOneQuestion(SiteId, dtExamQuestion, iIndex, ExamQuestionId).HtmlContent + "</li>\r\n";
                }
                RetHtml += "</ul>\r\n" +
                         "</div>\r\n" +
                         "<div class=break></div>\r\n";
                OAjaxOut.HtmlContent = RetHtml;
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.HtmlContent = ex.Message.ToString();
                OAjaxOut.InfoMessage = ex.Message.ToString();
            }
            return OAjaxOut;
        }


        public static AjaxOut DrawOneQuestion(
            string SiteId,
            DataTable dtExamQuestion,
            int QuestionIndex,
            string ExamQuestionId)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                string Html = "";
                string Title = (string)dtExamQuestion.Rows[QuestionIndex]["Title"];
                string Question = (string)dtExamQuestion.Rows[QuestionIndex]["Question"];
                string Type = (string)dtExamQuestion.Rows[QuestionIndex]["Type"];
                string StudentAnswer = (string)dtExamQuestion.Rows[QuestionIndex]["StudentAnswer"];
                int QuestionCorrectAnswer = int.Parse(dtExamQuestion.Rows[QuestionIndex]["CorrectAnswer"].ToString());

                if (string.IsNullOrEmpty(Question))
                {
                    Html += "<div class=CssQuestionTitle>Câu " + (QuestionIndex + 1) + ": " + Title + "</div>\r\n";
                }
                else
                {
                    Html += "<div class=CssQuestionTitle>Câu " + (QuestionIndex + 1) + ": " + Question + "</div>\r\n";
                }

                if (Type.ToLower().Equals("freetext"))
                {
                    Html += "<div class=CssQuestionType>Sinh viên viết bài tự luận dưới đây</div>\r\n" +
                            "<div class=CssListAnswer>\r\n";

                    for (int iIndex = 0; iIndex < 20; iIndex++)
                    {
                        Html += ".....................................................................................................................................................\r\n";
                    }

                    Html += "</div>\r\n";
                }
                OAjaxOut.HtmlContent = Html;
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
            }
            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod]
        public string GetProcessingText()
        {

            return "Đang đọc dữ liệu từ máy chủ";
        }

    }
}
